<template>
  <c-loading :loading="loading">
    <view class="container cart">
      <c-header>
        <view>购物车</view>
        <template #right>
          <view class="link-btn"  v-if="list.length" @tap="mamage = !mamage">{{ mamage ? '完成' : '管理' }}</view>
        </template>
      </c-header>
      <template v-if="list.length">
        <view class="block">
          <view v-for="item in list" :key="item.id" class="cart-box">
            <c-radio class="check-btn" fill :checked="select.has(item.skuId)" @change="onSelect(item)"></c-radio>
            <view class="cart-img">
              <c-img :src="item.smallImg" mode="aspectFill" />
            </view>
            <view class="cart-next">
              <view class="row2 goods-name">{{ item.goodsName }}</view>
              <view class="sku-name">{{ item.skuDesc }}</view>
              <view class="flex-between">
                <c-number precision-mini :precision="2" class="price" prefix="￥" :value="item.salePrice" />
                <c-counter v-model="item.qty" @change="onChange(item, $event)" :min="1" :max="item.isDeductStock ? item.stock : 999" />
              </view>
            </view>
          </view>
        </view>
        <view class="fixed-footer flex al-center shadow">
          <c-radio class="check-btn" :fill="select.size == list.length" :checked="select.size" @change="onSelect(true)">
            <text class="f-text">已选（{{ select.size }}）</text>
          </c-radio>
          <view class="grow"></view>
          <template v-if="mamage">
            <c-button size="inline" class="round" plain type="danger" :disabled="!select.size" @tap="onDelete">删除</c-button>
          </template>
          <template v-else>
            <view class="total">
              合计(不含运费)：
              <c-number precision-mini :precision="2" class="price" prefix="￥" :value="total" />
            </view>
            <c-button size="inline" class="round" @tap="onConfirm" :disabled="!select.size" type="danger">结算</c-button>
          </template>
        </view>
        <view class="end"></view>
      </template>
      <c-empty text="购物车空空" v-else>
        <view class="link-btn" @tap="router.switch('/pages/goods/classify/index')">去逛逛</view>
      </c-empty>
    </view>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CImg, CCounter, CNumber, CRadio, CEmpty, CHeader } from '@/components';
import { useLoading, useRouter } from '@/hooks';
import { View, Text } from '@tarojs/components';
import api from '@/api';
import { useDidShow } from '@tarojs/taro';
import { computed, ref } from 'vue';

const router = useRouter();
const list = ref([]);
const { loading, restart } = useLoading(async options => {
  list.value = await api.goods.cartList();
});
useDidShow(() => {
  if (!loading.value) {
    restart();
  }
});
const mamage = ref(false);
const select = ref(new Set());
const total = computed(() => {
  const items = [...select.value].map(skuId => list.value.find(a => a.skuId == skuId));
  return items.sum(a => a.salePrice * a.qty);
});
let setchange = {};
let timeoutz = null;
const onChange = (item, qty) => {
  setchange[item.id] = qty;
  if (timeoutz) clearTimeout(timeoutz);

  timeoutz = setTimeout(async () => {
    let lazy = Object.entries(setchange);
    for (let i = 0; i < lazy.length; i++) {
      const [id, qty] = lazy[i];
      await api.goods
        .cartUpdate({
          id,
          value: qty
        })
        .error()
        .catch(e => e); // 不终止行动
    }
    setchange = {};
  }, 500);
};

const onSelect = item => {
  if (item === true) {
    if (select.value.size == list.value.length) {
      select.value.clear();
    } else {
      list.value.forEach(item => select.value.add(item.skuId));
    }
  } else {
    if (select.value.has(item.skuId)) {
      select.value.delete(item.skuId);
    } else {
      select.value.add(item.skuId);
    }
  }
};

const onDelete = async () => {
  await api.goods.cartDelete({ ids: [...select.value] }).error();
  select.value.clear();
  restart();
};

const onConfirm = () => {
  const items = [...select.value].map(skuId => ({ skuId, qty: list.value.find(a => a.skuId == skuId)?.qty ?? 1 }));
  router.push('/pagesOrder/order/confirm', {
    items,
    fromCart: true
  });
};
</script>
<style lang="scss">
.manager {
  text-align: right;
  padding: 0 30px;
}
.cart-box {
  background-color: var(--color-caption);
  display: flex;
  align-items: center;
  padding: 20px 30px;
  border-top: var(--onepx) solid var(--color-line);
  .check-btn {
    flex-shrink: 0;
    margin-right: 15px;
  }
  .cart-img {
    flex-shrink: 0;
    width: 160px;
    height: 160px;
    margin-right: 20px;
    overflow: hidden;
    border-radius: 10px;
  }
  .cart-next {
    flex-grow: 1;
    align-self: stretch;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .price {
      color: var(--color-danger);
    }
    .sku-name {
      font-size: 22px;
      color: var(--color-gray);
      line-height: 36px;
      height: 36px;
    }
  }
}
.cart.container {
  .fixed-footer {
    .round {
      width: 160px;
      flex-shrink: 0;
      margin-left: 20px;
      flex-grow: 0;
    }
    .total {
      font-size: 24px;
      display: flex;
      align-items: center;
      .price {
        color: var(--color-danger);
        font-size: 30px;
      }
    }
  }
  .f-text {
    font-size: 24px;
    display: inline-block;
    vertical-align: baseline;
  }
}
</style>
